<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="提交用户" prop="submitUserName">
        <el-input
          v-model="queryParams.submitUserName"
          placeholder="请输入提交用户名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="提交时间" prop="submitTime">
        <el-date-picker
          v-model="queryParams.submitTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select
          v-model="queryParams.auditStatus"
          placeholder="请选择审核状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_AUDIT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['product:audit:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="审核主键" align="center" prop="id" />
      <el-table-column label="商品编号" align="center" prop="productId" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="提交用户编号" align="center" prop="submitUserId" />
      <el-table-column label="提交用户名" align="center" prop="submitUserName" width="120px" />
      <el-table-column
        label="提交时间"
        align="center"
        prop="submitTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PRODUCT_AUDIT" :value="scope.row.auditStatus" />
        </template>
      </el-table-column>
      <el-table-column label="审核人ID" align="center" prop="auditUserId" />
      <el-table-column label="审核人姓名" align="center" prop="auditUserName" />
      <el-table-column
        label="审核时间"
        align="center"
        prop="auditTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="驳回原因" align="center" prop="auditRemark" />
      <el-table-column label="当前版本号" align="center" prop="currentVersion" />
      <el-table-column label="操作" align="center" min-width="120px" fixed="right">
        <template #default="scope">
          <el-button
            v-if="hasAdminRole && !scope.row.auditStatus"
            link
            type="primary"
            @click="handleAudit(scope.row)"
            v-hasPermi="['product:audit:update']"
          >
            审核
          </el-button>
          <el-button
            v-else
            link
            type="warning"
            @click="handleAudit(scope.row)"
          >
            详情
          </el-button>
          <!-- 撤销按钮，仅普通用户且待审核状态可见 -->
          <el-button
            v-if="!hasAdminRole && !scope.row.auditStatus"
            link
            type="danger"
            @click="handleRevoke(scope.row)"
          >
            撤销
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AuditForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AuditApi, AuditVO } from '@/api/mall/product/audit'
import AuditForm from './AuditForm.vue'
import { useAuditStore } from '@/store/modules/audit'
import { useUserStore } from '@/store/modules/user'
import { useEmitt } from '@/hooks/web/useEmitt'

/** 商品审核 列表 */
defineOptions({ name: 'Audit' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { push, currentRoute } = useRouter() // 路由
const loading = ref(true) // 列表的加载中
const list = ref<AuditVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productName: undefined,
  submitUserName: undefined,
  submitTime: [],
  auditStatus: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const auditStore = useAuditStore()
const { emitter } = useEmitt()

// 恢复管理员角色判断
const hasAdminRole = computed(() => {
  const userStore = useUserStore()
  const roles = userStore.roles
  return roles.includes('super_admin') || roles.includes('tenant_admin')
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AuditApi.getAuditPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 查看审核详情 */
const handleAudit = (row: AuditVO) => {
  // 使用 store 存储数据
  auditStore.setCurrentAudit(row)
  push({ name: 'ProductAuditDetail' })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AuditApi.exportAudit(queryParams)
    download.excel(data, '商品审核.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 撤销审核操作 */
const handleRevoke = async (row: AuditVO) => {
  try {
    await message.confirm(`是否撤销"${row.productName}"的审核？`)
    await AuditApi.updateAudit({ ...row, auditStatus: 3 }) // 只传需要的字段更好
    message.success('审核撤销完成')
    await getList() // 等待接口返回后再刷新
  } catch (error) {
    if (error !== 'cancel') { // 用户取消不提示
      console.error('审核撤销失败:', error)
      message.error('审核撤销失败')
    }
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  // 监听全局事件，收到后刷新列表
  emitter.on('refresh-list', getList)
})

/** 监听路由变化，当从审核详情页面返回时刷新数据 */
watch(
  () => currentRoute.value.name,
  (newRouteName, oldRouteName) => {
    // 如果从审核详情页面返回到审核列表页面，刷新数据
    if (oldRouteName === 'ProductAuditDetail' && newRouteName === 'Audit') {
      getList()
    }
  }
)

/** 销毁 */
onBeforeUnmount(() => {
  emitter.off('refresh-list', getList)
})

</script>